<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>群组管理</el-breadcrumb-item>
      <el-breadcrumb-item>群组管理</el-breadcrumb-item>
      <el-breadcrumb-item>群组用户</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表主体部分 -->
    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="25">
        <el-col :span="10">
          <!-- 搜索区域 -->
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 搜索按钮 -->
        <el-col :span="3" v-if="this.name === '用户管理群组'">
          <el-button type="primary" @click="showaddDialog()">添加用户</el-button>
        </el-col>

        <el-col :span="6">
          
        </el-col>
        <!-- 退出按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="back()">返回</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 border边框 stripe隔行变色-->
      <el-table :data="userList" border="" stripe="">
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="name"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>

        <el-table-column label="操作" v-if="this.name === '用户管理群组'">
          <template slot-scope="scope">
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.name)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum" :page-sizes="[1, 2, 5, 100]" :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">

      <el-form :model="addForm" ref="addFormRef" label-width="70px">

        <el-form-item label="" prop="name">

          <!-- 用户列表 border边框 stripe隔行变色-->
          <el-table :data="alluserList" border="" stripe="">
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="用户名" prop="name"></el-table-column>
            <el-table-column label="角色" prop="role"></el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 新增 -->
                <el-button type="primary" icon="el-icon-circle-plus" size="mini" @click="adduserDialog(scope.row.name)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div>
            <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1"
              :current-page="queryInfo1.pageNum1" :page-sizes="[1, 2, 5, 100]" :page-size="queryInfo1.pageSize1"
              layout="total, sizes, prev, pager, next, jumper" :total="total1">
            </el-pagination>
          </div>

        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>
  
<script>
import Vue from "vue";
export default {
  created() {
    this.tenantname = window.sessionStorage.getItem("tenantname");
    this.groupname = window.sessionStorage.getItem("groupname");
    this.gid = window.sessionStorage.getItem("gid");
    this.getUserList();
  },

  data() {
    return {
      ...this.$route.query,
      //查询信息实体
      queryInfo: {
        query: "", //查询信息
        pageNum: 1, //当前页
        pageSize: 5, //每一页最大数
      },
      total: 0, 
      queryInfo1: {
        query1: "", //查询信息
        pageNum1: 1, //当前页
        pageSize1: 5, //每一页最大数
      },
      total1:0,
      userList: [], //用户列表
      user: {},
      alluserList: [],  //全部用户
      //总记录数
      addDialogVisible: false, //对话框状态
      gid: "",
      groupname: "",
      tenantname: "",
      //添加表单信息
      addForm: {
        username: "",
      },

      //添加表单验证
      addFormRules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 12,
            message: "长度在 1 到 12 个字符",
            trigger: "blur",
          },
        ],
      },

    };
  },
  methods: {
    //获取所有用户
    async getUserList() {
      await this.$http({
        method: "post",
        url: "/usersInGroupFuzzyY",
        data: {
          query: this.queryInfo.query,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
          gid: this.gid,
        },
      }).then((res) => {
        // this.addlist(response.data.data.list);

        this.userList=res.data.data.list
        console.log(this.userList)
        let list = [];
        this.addlist(list);
        this.total = res.data.data.total;
      });
    },

    addlist(list) {
      // let demolist = [];
      // list.forEach((username) => {

      //   demolist.push({ "username": username })

      // });
      // this.userList = demolist
      this.userList.forEach((user) => {
        user = JSON.parse(JSON.stringify(user));

        if (user.level == "3") {
          Vue.set(user, "role", "用户"); //正确姿势
          list.push(user);
        }
        if (user.level == "4") {
          Vue.set(user, "role", "答者"); //正确姿势
          list.push(user);
        }
        this.userList = list;
        console.log(this.userList)

      });
    },

    //得到未加入群组用户列表
    async getallUserList() {
      await this.$http({
        method: "post",
        url: "/getRestUser",
        data: {
          query: this.queryInfo1.query1,
          pageNum: this.queryInfo1.pageNum1,
          pageSize: this.queryInfo1.pageSize1,
          gid: this.gid,
          name: this.tenantname
        },
      }).then((res) => {   
        this.alluserList=res.data.data.list

        let list = [];
        this.addlist1(list);
        this.total1 = res.data.data.total;
      });
    },
    addlist1(list) {
      this.alluserList.forEach((user) => {
        user = JSON.parse(JSON.stringify(user));

        if (user.level == "3") {
          Vue.set(user, "role", "用户"); //正确姿势
          list.push(user);
        }
        if (user.level == "4") {
          Vue.set(user, "role", "答者"); //正确姿势
          list.push(user);
        }
        this.alluserList = list;


      });
    },
    
    //最大数
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },

    //pageNum触发的动作
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },

    //最大数
    handleSizeChange1(newSize) {
      this.queryInfo1.pageSize1 = newSize;
      this.getallUserList();
    },

    //pageNum触发的动作
    handleCurrentChange1(newPage) {
      this.queryInfo1.pageNum1 = newPage;
      this.getallUserList();
    },

    //监听添加用户
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    
    //根据主键删除用户
    async deleteUser(name) {
      const confirmResult = await this.$confirm(
        "此操作将永远删除用户，是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult != "confirm") {
        //取消
        return this.$message.info("已取消删除");
      }
      await this.$http({
        method: "post",
        url: "/deleteUserFromGroup",
        data: {
          username: name,
          gId: this.gid
        },
      }).then((res) => {
        if (res.data.code == "666") {

          this.$message.success(res.data.message);
          this.getUserList();
        }
        else {
          this.$message.error(res.data.message);
        }

      });

    },
    async showaddDialog() {
      this.getallUserList() 
      this.addDialogVisible = true;
    },
    back(){
      if(this.name==="用户管理群组"){
      this.$router.push({ path: "/groups" }); //页面路由跳转
      }else if(this.name==="租户管理群组"){
        this.$router.push({path:"/groupt"});
      }else{
        console.log("出现异常");
      }

    },
    //群组添加用户
    adduserDialog(name) {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        //添加用户>>>?????表单提交验证
        await this.$http({
          method: "post",
          url: "/addUserToGroup",
          data: {
            gId: this.gid,
            username: name
          },
        }).then((res) => {
          const response = res.data
          if (response.code == "666") {
            this.$message.success(response.message);
            this.addDialogVisible = false;
            this.getUserList();
          } else {
            this.$message.error(response.message);
          }
        });
      });
    },
    
  },
};
</script>
  
<style lang="less" scoped>
/* 面包屑样式 */
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
</style>